package com.slmxz.tms.system.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.slmxz.tms.common.annotation.Log;
import com.slmxz.tms.common.constant.SystemConstants;
import com.slmxz.tms.common.enums.LogModuleEnum;
import com.slmxz.tms.common.model.Query;
import com.slmxz.tms.common.support.Condition;
import com.slmxz.tms.common.util.StringExtendUtil;
import com.slmxz.tms.system.listener.UserImportListener;
import com.slmxz.tms.system.model.form.*;
import com.slmxz.tms.system.model.vo.*;
import com.slmxz.tms.system.service.UserService;
import com.slmxz.tms.common.annotation.RepeatSubmit;
import com.slmxz.tms.common.enums.ContactType;
import com.slmxz.tms.common.result.PageResult;
import com.slmxz.tms.common.result.Result;
import com.slmxz.tms.common.util.ExcelUtils;
import com.slmxz.tms.core.security.util.SecurityUtils;
import com.slmxz.tms.system.model.dto.UserExportDTO;
import com.slmxz.tms.system.model.dto.UserImportDTO;
import com.slmxz.tms.system.model.entity.User;
import com.slmxz.tms.system.model.query.UserPageQuery;
import com.slmxz.tms.system.model.form.*;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户控制层
 *
 * @author albert
 * @date 2024-11-30
 */
@Tag(name = "02.用户接口")
@RestController
@RequestMapping("/system/user")
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;

    @GetMapping("/page")
    @Operation(summary = "用户分页列表")
    public PageResult<UserVO> page(@ParameterObject Query query, UserVO user) {
        IPage<UserVO> result = this.userService.selectPage(Condition.getPage(query),user);
        return PageResult.success(result);
    }

    @Operation(summary = "新增用户")
    @PostMapping
    @RepeatSubmit
    @Log(value = "新增用户", module = LogModuleEnum.USER)
    public Result<?> saveUser(@RequestBody @Valid UserForm userForm) throws Exception {
        boolean result = this.userService.saveUser(userForm);
        return Result.result(result);
    }

    @Operation(summary = "用户表单数据")
    @GetMapping("/{userId}/form")
    public Result<UserForm> getUserForm(
            @Parameter(description = "用户ID") @PathVariable Long userId
    ) {
        UserForm formData = this.userService.getUserFormData(userId);
        return Result.success(formData);
    }

    @Operation(summary = "修改用户")
    @PutMapping(value = "/update")
    @Log(value = "修改用户", module = LogModuleEnum.USER)
    @PreAuthorize("@ss.hasPerm('sys:user:edit')")
    public Result<?> updateUser(@RequestBody @Validated UserForm userForm) {
        boolean result = this.userService.updateUser(userForm);
        return Result.result(result);
    }

    @Operation(summary = "删除用户")
    @DeleteMapping("delete/{ids}")
    @PreAuthorize("@ss.hasPerm('sys:user:delete')")
    @Log(value = "删除用户", module = LogModuleEnum.USER)
    public Result<Void> deleteUsers(
            @Parameter(description = "用户ID，多个以英文逗号(,)分割") @PathVariable String ids
    ) {
        boolean result = this.userService.deleteUsers(ids);
        return Result.result(result);
    }

    @Operation(summary = "启用用户")
    @PutMapping(value = "/enableUser/{ids}")
    @PreAuthorize("@ss.hasPerm('sys:user:delete')")
    @Log(value = "启用用户", module = LogModuleEnum.USER)
    public Result<Void> enableUser(@Parameter(description = "用户ID") @PathVariable String ids
    ) {
        // 启用用户
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .collect(Collectors.toList());
        boolean result = this.userService.update(new LambdaUpdateWrapper<User>()
                .in(User::getId, idList)
                .eq(User::getIsDeleted, SystemConstants.DELETED)
                .set(User::getIsDeleted, SystemConstants.UN_DELETED)
        );
        return Result.result(result);
    }

    @Operation(summary = "获取当前登录用户信息")
    @GetMapping("/me")
    public Result<UserInfoVO> getCurrentUserInfo() {
        UserInfoVO userInfoVO = this.userService.getCurrentUserInfo();
        return Result.success(userInfoVO);
    }

    @Operation(summary = "用户导入模板下载")
    @GetMapping("/template")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        String fileName = "用户导入模板.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));

        String fileClassPath = "templates" + File.separator + "excel" + File.separator + fileName;
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(fileClassPath);

        ServletOutputStream outputStream = response.getOutputStream();
        ExcelWriter excelWriter = EasyExcel.write(outputStream).withTemplate(inputStream).build();

        excelWriter.finish();
    }

    @Operation(summary = "导入用户")
    @PostMapping("/import")
    public Result<String> importUsers(MultipartFile file) throws IOException {
        UserImportListener listener = new UserImportListener();
        String msg = ExcelUtils.importExcel(file.getInputStream(), UserImportDTO.class, listener);
        return Result.success(msg);
    }

    @Operation(summary = "导出用户")
    @GetMapping("/export")
    public void exportUsers(UserPageQuery queryParams, HttpServletResponse response) throws IOException {
        String fileName = "用户列表.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));

        List<UserExportDTO> exportUserList = this.userService.listExportUsers(queryParams);
        EasyExcel.write(response.getOutputStream(), UserExportDTO.class).sheet("用户列表")
                .doWrite(exportUserList);
    }

    @Operation(summary = "获取个人中心用户信息")
    @GetMapping("/profile")
    public Result<UserProfileVO> getUserProfile() {
        Long userId = SecurityUtils.getUserId();
        UserProfileVO userProfile = this.userService.getUserProfile(userId);
        return Result.success(userProfile);
    }

    @Operation(summary = "修改个人中心用户信息")
    @PutMapping("/profile")
    public Result<?> updateUserProfile(@RequestBody UserProfileForm formData) {
        boolean result = this.userService.updateUserProfile(formData);
        return Result.result(result);
    }

    @Operation(summary = "重置用户密码")
    @PutMapping(value = "/{userId}/password/reset")
    @PreAuthorize("@ss.hasPerm('sys:user:password:reset')")
    public Result<?> resetPassword(
            @Parameter(description = "用户ID") @PathVariable Long userId
    ) {
        return Result.success(this.userService.resetPassword(userId));
    }

    @Operation(summary = "修改密码")
    @PutMapping(value = "/password")
    public Result<?> changePassword(
            @RequestBody PasswordChangeForm data
    ) {
        Long currUserId = SecurityUtils.getUserId();
        boolean result = this.userService.changePassword(currUserId, data);
        return Result.result(result);
    }

    @Operation(summary = "发送短信/邮箱验证码")
    @PostMapping(value = "/send-verification-code")
    public Result<?> sendVerificationCode(
            @Parameter(description = "联系方式（手机号码或邮箱地址）", required = true) @RequestParam String contact,
            @Parameter(description = "联系方式类型（Mobile或Email）", required = true) @RequestParam ContactType contactType
    ) {
        boolean result = this.userService.sendVerificationCode(contact, contactType);
        return Result.result(result);
    }

    @Operation(summary = "绑定个人中心用户手机号")
    @PutMapping(value = "/mobile")
    public Result<?> bindMobile(
            @RequestBody @Validated MobileBindingForm data
    ) {
        boolean result = this.userService.bindMobile(data);
        return Result.result(result);
    }


    @Operation(summary = "绑定个人中心用户邮箱")
    @PutMapping(value = "/email")
    public Result<?> bindEmail(
            @RequestBody @Validated EmailChangeForm data
    ) {
        boolean result = this.userService.bindEmail(data);
        return Result.result(result);
    }




}
